package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.*;
import com.example.demo.service.*;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Controller
public class MainController {
    LoginService loginService = new LoginService();
    String IP;
    String name;
    String xkkz_id;
    String kch_id;
    String kcmc_tmp;

    Map<String,String> cookies = new HashMap<>(); //访问资源所需cookies

    String do_jxb_id; //变量，目前无法知道如何计算


    @Resource
    VariableParameterService variableParameterService;
    @Resource
    CourseService courseService;
    @Resource
    Course2Service course2Service;
    @Resource
    CourseTableService courseTableService;

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String toIndex(Model model){
        List<CourseTable> courseTableList = new ArrayList<>();
        courseTableList = courseTableService.list();
        model.addAttribute("courseTableList",courseTableList);
        return "/index";
    }


    //获取登录后访问其他页面所需的cookie
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String beginLogin(User user) throws Exception{

        name = user.getName();
        String password = user.getPassword();
        IP = user.getIP();
        kch_id = user.getKch_id();
        kcmc_tmp = user.getKcmc_tmp();

        VariableParameter variableParameter = variableParameterService.getByName(name);
        if(variableParameter!=null && variableParameter.getName()!=null && courseService.getByName(name)!=null){

            cookies.put("JSESSIONID",variableParameter.getCookies());
            return "redirect:/getElective";
        }

        //模拟登录，获取登录参数cookies_innet
        Connection connection = loginService.getConnection(IP,"/xtgl/login_slogin.html");
        Response response = loginService.getReponse(connection);
        Document document = loginService.getDocument(response);
        List<Element> elements = loginService.getElements(document,"form");
        Map<String,String> cookies_innet = loginService.getCookies(response);
        String csrftoken = loginService.getCsrftoken(cookies_innet,IP);
        password = loginService.getRSApublickey(IP,cookies_innet,password);

        //登录,获取csrftoken并二次加密password
        connection = loginService.getConnection(IP,"/xtgl/login_slogin.html",cookies_innet);
        connection.data("csrftoken",csrftoken);
        connection.data("yhm",name);
        connection.data("mm",password);
        connection.data("mm",password);
        connection.cookies(cookies_innet).ignoreContentType(true).method(Connection.Method.POST).execute();
        cookies = connection.request().cookies();
        cookies.remove("rememberMe");//去除获取的cookies中无用的参数
        response = connection.followRedirects(true).execute();
        document = loginService.getDocument(response);
        if(document.getElementById("tips") == null){
            System.out.println("欢迎登录");
            System.out.println(cookies);
            String cookie = cookies.get("JSESSIONID");
            variableParameter = new VariableParameter();
            variableParameter.setCookies(cookie);
            variableParameter.setName(name);
            variableParameterService.removeByName(name);
            variableParameterService.save(variableParameter);
            return "redirect:/getMarginElective";
        }else{
            System.out.println(document.getElementById("tips").text());
            System.out.println(response.cookies());
            return "false";
        }

    }

    //获取余量选修课表,在到这个方法前先判断course是否有参数
    @RequestMapping(value = "/getMarginElective")
    public String getMarginElective() throws Exception {
//        System.out.println(courseService);
        //判断是否含有cookies
        if(cookies == null){
            VariableParameter variableParameter = variableParameterService.getByName(name);
            if(variableParameter.getName() == null){
                return "redirect:/login";
            }
            cookies.put("JSESSIONID",variableParameter.getCookies());
        }
        Course course = courseService.getByName(name);
        if(course == null || course.getName() == null){

            //获取查询课表的参数course 和  xkkz_id,该变量一般为固定，但每轮抢课会改变,firstXkkzId
            Connection connection = loginService.getConnection(IP,"/xsxk/zzxkyzb_cxZzxkYzbIndex.html?gnmkdm=N253512&layout=default&su=" + name);
            connection.cookies(cookies).method(Connection.Method.POST).ignoreContentType(true).execute();
            xkkz_id = connection.get().getElementById("firstXkkzId").val();
            Course course1 = new Course();
            course1 = courseService.getCourse(connection);
            course1.setName(name);
            course1.setXkkz_id(xkkz_id);
            courseService.save(course1);
            System.out.println("获取course参数成功");
        }

        Map<String,String> courses = courseService.getCourses(name);
        courses.put("yl_list[0]","1");//设置该参数可以查询余量，若需查询所有课表可以注释该行
        courses.remove("id");
        courses.remove("name");
        courses.remove("xkkz_id");
        Connection connection = loginService.getConnection(IP,"/xsxk/zzxkyzb_cxZzxkYzbPartDisplay.html?gnmkdm=N253512&su=" + name);
        loginService.getDatasReponse(connection,cookies,courses);
        connection.cookies(cookies).method(Connection.Method.POST).ignoreContentType(true).execute();
        Response response = connection.followRedirects(true).execute();
        System.out.println(response.body());
        JSONObject jsonObject = JSON.parseObject(response.body());
        JSONArray gradeTable = JSON.parseArray(jsonObject.getString("tmpList"));

        //向数据库存放前先清空原先表内容
        courseTableService.remove(new QueryWrapper<>());

        for (Iterator iterator = gradeTable.iterator(); iterator.hasNext();) {
            JSONObject lesson = (JSONObject) iterator.next();
            String kcmc_tmp = "("+lesson.getString("kch")+")"+lesson.getString("kcmc")+" - "+lesson.getString("xf")+" 学分";
            System.out.println(lesson.getString("jxb_id") + " " +
                    lesson.getString("jxbmc") + " " +
                    lesson.getString("kch_id") + " " +
                    lesson.getString("kcmc")+ " "+
                    kcmc_tmp);
            CourseTable courseTable = new CourseTable();
            courseTable.setJxb_id(lesson.getString("jxb_id"));
            courseTable.setJxbmc(lesson.getString("jxbmc"));
            courseTable.setKch_id(lesson.getString("kch_id"));
            courseTable.setKcmc(lesson.getString("kcmc"));
            courseTable.setKcmc_tmp(kcmc_tmp);
            courseTableService.save(courseTable);
        }
        return "redirect:/";
    }


    //选课
    @RequestMapping(value = "/getElective")
    public String getElective() throws Exception {

        if(course2Service.getByName(name)==null || course2Service.getByName(name).getName()==null){
            Course course = courseService.getByName(name);
            xkkz_id = course.getXkkz_id();
            Course2 course2= course2Service.getCourse2(name,courseService,kch_id,xkkz_id);
            course2Service.save(course2);
        }

        Course course = courseService.getByName(name);
        xkkz_id = course.getXkkz_id();
        //获取一个变量do_jxb_id
        Map<String,String> courses = course2Service.getCourses(name,kch_id,xkkz_id);
        Connection connection = loginService.getConnection(IP,"/xsxk/zzxkyzbjk_cxJxbWithKchZzxkYzb.html?gnmkdm=N253512&su=" + name);
        courses.remove("kch_id");
        courses.remove("name");
        courses.remove("id");
        courses.put("kch_id",kch_id);
        courses.put("yl_list[0]","1");
        loginService.getDatasReponse(connection,cookies,courses);
        connection.cookies(cookies).method(Connection.Method.POST).ignoreContentType(true).execute();
        Response response = connection.followRedirects(true).execute();
        //输出公选课老师信息
        JSONArray gradeTable = JSON.parseArray(response.body());
        for (Iterator iterator = gradeTable.iterator(); iterator.hasNext();) {
            JSONObject lesson = (JSONObject) iterator.next();
            System.out.println(lesson.getString("kkxymc") + " " +
                    lesson.getString("jxb_id") + " " +
                    lesson.getString("kcgsmc") + " " +
                    lesson.getString("do_jxb_id")+ " " +
                    lesson.getString("jsxx"));
            do_jxb_id = lesson.getString("do_jxb_id");
        }
        System.out.println(do_jxb_id);



        DataService dataService = new DataService();
        Map<String,String> datas = dataService.getDatas(name,course2Service,do_jxb_id,kcmc_tmp,kch_id);
        connection = loginService.getConnection(IP,"/xsxk/zzxkyzbjk_xkBcZyZzxkYzb.html?gnmkdm=N253512&su=" + name);
        loginService.getDatasReponse(connection,cookies,datas);
        connection.cookies(cookies).method(Connection.Method.POST).ignoreContentType(true).execute();
        response = connection.followRedirects(true).execute();
        System.out.println(response);

        //抢课成功，进行删库,以便再次登陆时重新获取cookies
        variableParameterService.removeByName(name);
        return "success";
    }
}
